package com.hub.service.asset.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hub.service.asset.IPartsInfoFilesService;
import com.hub.service.impl.BaseServiceImpl;
import com.hub.dto.asset.PartsInfoFileDto;
import com.hub.entity.asset.PartsInfoFileEntity;
import com.hub.frame.consts.ConstantUtil;
import com.hub.mapper.asset.PartsInfoFilesMapper;
import com.hub.model.asset.PartsInfoFileModel;
import com.hub.utils.ApiResultObject;
import org.dozer.Mapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author hub
 * @since 2020-05-21
 */
@Service
public class PartsInfoFilesServiceImpl extends BaseServiceImpl<PartsInfoFilesMapper, PartsInfoFileEntity> implements IPartsInfoFilesService {

    @Autowired
    private Mapper mapper;

    /**
     * 根据配件ID，获取该配件所有的附件信息
     * @param assetId
     * @return
     */
    public ApiResultObject loadPartsFilesByAssetId(long assetId) {

        QueryWrapper<PartsInfoFileEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("parts_id",assetId);
        wrapper.eq("active_flg", ConstantUtil.YES);

        List<PartsInfoFileEntity> list = baseMapper.selectList(wrapper);
        List<PartsInfoFileModel> modelList = new ArrayList<>();

        for (PartsInfoFileEntity entity:list) {
            modelList.add(mapper.map(entity,PartsInfoFileModel.class));
        }

        return ApiResultObject.success(modelList);
    }

    /**
     * 新增配件基础信息文件
     * @param request
     * @return
     */
    public ApiResultObject addPartsInfoFile(PartsInfoFileDto request) {

        //保存数据库
        PartsInfoFileEntity entity = mapper.map(request, PartsInfoFileEntity.class);
        if(this.save(entity)){
            return ApiResultObject.success("新增配件基础信息文件成功!");
        }
        return ApiResultObject.failed("资产配件文件保存数据库失败!");
    }

    /**
     * 批量新增配件基础信息文件
     * @param request
     * @return
     */
    @Transactional
    public ApiResultObject addPartsInfoFiles(List<PartsInfoFileDto> request) {

        for (PartsInfoFileDto model:request) {
            //保存数据库
            PartsInfoFileEntity entity = mapper.map(model, PartsInfoFileEntity.class);
            if(!this.save(entity)){
                return ApiResultObject.failed("配件信息文件保存数据库失败!");
            }
        }
        return ApiResultObject.success("新增配件基础信息文件成功!");
    }

    /**
     * 删除配件基础信息文件-逻辑删除
     * @param id
     * @return
     */
    public ApiResultObject removePartsInfoFile(Long id) {

        if(id< 1)
            return ApiResultObject.failed("参数异常: 配件信息附件ID异常!");

        if(this.removeById(id)){
            return ApiResultObject.success("配件基础信息附件删除成功!");
        }
        return ApiResultObject.failed("配件基础信息附件异常，删除失败!");
    }
}
